package A9_JUC辅助类;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 *
 *  抢车位：多人抢多个资源
 * @Author: KingWang
 * @Date: 2021/5/23
 * @Desc:
 **/
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i <10 ; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 抢到车位");
                    int useTime = new Random().nextInt(9) + 1;
                    TimeUnit.SECONDS.sleep(useTime);
                    System.out.println(Thread.currentThread().getName() + "\t 离开车位,占用时间" + useTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
